const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const port = 3000;

// 配置跨域，方便前端请求
app.use(cors());
app.use(bodyParser.json());

// 创建MySQL连接池
const pool = mysql.createPool({
  host: 'localhost', // MySQL主机地址，根据实际修改
  user: 'root', // MySQL用户名，根据实际修改
  password: '123456', // MySQL密码，根据实际修改
  database: 'library' // 使用的数据库名，根据实际修改
});

// 注册接口
app.post('/register', (req, res) => {
  const { username, password } = req.body;
  pool.getConnection((err, connection) => {
    if (err) {
      console.error(err);
      return res.json({ success: false, message: '数据库连接错误' });
    }
    const query = 'INSERT INTO users (username, password) VALUES (?,?)';
    connection.query(query, [username, password], (error, results) => {
      connection.release();
      if (error) {
        console.error(error);
        return res.json({ success: false, message: '注册失败，用户名可能已存在' });
      }
      res.json({ success: true, message: '注册成功' });
    });
  });
});

// 登录接口
app.post('/login', (req, res) => {
  const { username, password } = req.body;
  pool.getConnection((err, connection) => {
    if (err) {
      console.error(err);
      return res.json({ success: false, message: '数据库连接错误' });
    }
    const query = 'SELECT * FROM users WHERE username =? AND password =?';
    connection.query(query, [username, password], (error, results) => {
      connection.release();
      if (error) {
        console.error(error);
        return res.json({ success: false, message: '登录失败' });
      }
      if (results.length > 0) {
        res.json({ success: true, message: '登录成功' });
      } else {
        res.json({ success: false, message: '用户名或密码错误' });
      }
    });
  });
});
app.use(express.static('public'));
app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});